//
// Created by v on 2025/11/18.
//

#include "CMStorageBase.h"
#include "utils/rt_print.h"

CMStorageBase::CMStorageBase(CMStorageManager *manager)
{
    pri_manager = manager;
    pri_storage = NULL;
    time_per_file = 20*60;
    size_per_file = 50*1024*1024;
    storage_limit_as_free = 1*1024*1024*1024;
    file_ext = "h264";
}
CMStorageBase::~CMStorageBase()
{
    deinit();
}
int CMStorageBase::savePath(const char *path)
{
    save_path = path;
    return 0;
}
int CMStorageBase::saveStrategy(int s)
{
    save_strategy = s;
    return s;
}
int CMStorageBase::storageLimitAsFree(size_t free_limit)
{
    storage_limit_as_free = free_limit;
    return 0;
}
int CMStorageBase::timePerFile(uint64_t time)
{
    time_per_file = time;
    return 0;
}
int CMStorageBase::sizePerFile(uint64_t size)
{
    size_per_file = size;
    return 0;
}
int CMStorageBase::ext_name(const char *ext)
{
    file_ext = ext;
    return 0;
}
int CMStorageBase::init()
{
    int ret = cm_avstorage_init(&pri_storage, save_path.c_str(),
        time_per_file, size_per_file, file_ext.c_str());
    if (ret < 0)
    {
        rterror("init failed [%d]\n", ret);
        return -2;
    }
    return ret;
}
int CMStorageBase::deinit()
{
    if (pri_storage)
    {
        cm_avstorage_deinit(&pri_storage);
    }
    return 0;
}
int CMStorageBase::pushData(unsigned char *data, size_t size, const char *ext)
{
    bool for_new = false;
    if (pri_manager)
    {
        if (pri_manager->free_size() < storage_limit_as_free)
        {
            for_new = true;
        }
    }
    int ret = cm_avstorage_v_push(pri_storage, data, size, for_new);
    rtdebug("push data [%d] force_new [%d]\n", ret, for_new);
    return ret;
}
